package com.af.system.Utils;

import com.af.system.servlet.interceptor.RestTemplateRequestInterceptor;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author : zhenyun.su
 * @comment : RestTemplate工具类
 * @since : 2022/12/7
 */

public final class AfRestTemplateUtil {

    /*
     * @comment : 将请求头中Authorization的token获取，并新建拦截器RestTemplateRequestInterceptor放到RestTemplate
     */
    public static void setRestTemplateToken(RestTemplate restTemplate, HttpServletRequest request){
        String tokenValue = request.getHeader(RestTemplateRequestInterceptor.TOKEN_KEY);
        RestTemplateRequestInterceptor requestInterceptor= new RestTemplateRequestInterceptor(tokenValue);
        requestInterceptor = (RestTemplateRequestInterceptor)addRequestInterceptor(restTemplate, requestInterceptor);
        requestInterceptor.setTokenValue(tokenValue);
    }

    /*
     * @comment : 将自定义拦截器添加到restTemplate，比如在请求头上添加Authorization认证token信息 
     */
    public static ClientHttpRequestInterceptor addRequestInterceptor(RestTemplate restTemplate, ClientHttpRequestInterceptor requestInterceptor){
        List<ClientHttpRequestInterceptor> interceptorList = restTemplate.getInterceptors();
        for (ClientHttpRequestInterceptor interceptor : interceptorList) {
            if (requestInterceptor.getClass().getSimpleName().equals(interceptor.getClass().getSimpleName())){
                return interceptor;
            }
        }
        interceptorList.add(requestInterceptor);
        return requestInterceptor;
    }
}
